import BundleManager from "../core/BundleManager";
import LogUtil from "../utils/LogUtil";
import { StorageUtil } from "../utils/StorageUtil";

const { ccclass, property } = cc._decorator;
/**
 * 背景音乐
 */
@ccclass
export default class BaseMusicPrefab extends cc.Component {
    public static instance: BaseMusicPrefab = null;
    private static MUSIC_VOLUMN_KEY: string = "musicVolumn";

    public static musicVolumn: number = 1;

    public static play(url: string) {

    }

    public static playByBundle(url: string,bundleName: string) {
        BundleManager.ins().loadBundle(bundleName,url,(clip:cc.AudioClip) => {
            if (clip) {
                BaseMusicPrefab.instance.node.getComponent(cc.AudioSource).clip = clip;
                BaseMusicPrefab.instance.node.getComponent(cc.AudioSource).volume = this.musicVolumn;
                BaseMusicPrefab.instance.node.getComponent(cc.AudioSource).play();
                BaseMusicPrefab.instance.node.getComponent(cc.AudioSource).loop = true;
            }
        },cc.AudioClip);
    }

    public static changeVolumn(nowVolumn: number) {
        this.musicVolumn = nowVolumn;
        BaseMusicPrefab.instance.node.getComponent(cc.AudioSource).volume = nowVolumn;
        StorageUtil.ins().setItem(BaseMusicPrefab.MUSIC_VOLUMN_KEY, this.musicVolumn.toString());
    }

    private static preInit() {
        this.musicVolumn = parseFloat(StorageUtil.ins().getItem(BaseMusicPrefab.MUSIC_VOLUMN_KEY));
        if (isNaN(this.musicVolumn)) {
            this.musicVolumn = 1;
        }
    }

    public static preLoad(): Promise<void> {
        return new Promise((resolve, reject) => {
            cc.resources.load("prefabs/BaseMusicPrefab", cc.Prefab, (error: Error, asset: any) => {
                if (error) {
                    LogUtil.error(error);
                    reject('error');
                } else {
                    BaseMusicPrefab.instance = cc.instantiate(asset).getComponent(BaseMusicPrefab);
                    BaseMusicPrefab.instance.node.setParent(cc.Canvas.instance.node);
                    this.preInit();
                    resolve();
                }
            })
        });
    }

    public static destory() {
        if (BaseMusicPrefab.instance) {
            BaseMusicPrefab.instance.node.getComponent(cc.AudioSource).stop();
            BaseMusicPrefab.instance.node.destroy();
        }
        BaseMusicPrefab.instance = null;
    }

    public static pause(){
        if (BaseMusicPrefab.instance) {
            BaseMusicPrefab.instance.getComponent(cc.AudioSource).stop();
        }
    }
    
}